﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SMS.Business;
using SMS.DAL;

namespace SMS.Orders.Returns
{
    public partial class Returns : System.Web.UI.Page
    {
        private List<OrderItem> OrderItems
        {
            set
            {
                if (ViewState["OrderItems"] == null)
                    ViewState["OrderItems"] = new List<OrderItem>();
                else
                    ViewState["OrderItems"] = value;
            }
            get
            {
                if (ViewState["OrderItems"] == null)
                    return new List<OrderItem>();
                else
                    return (List<OrderItem>) ViewState["OrderItems"];
            }
        }
        public decimal? Total
        {
            set
            {
                ViewState["Total"] = value;
            }
            get
            {
                return (decimal)ViewState["Total"];
            }
        }
        public decimal Paid
        {
            set;
            get;
        }

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            OrderItems = new List<OrderItem>();
            OrderBusiness OrderBus = new OrderBusiness();
            Order order = OrderBus.GetByID(int.Parse(txtOrderID.Text));
            Total = order.TotalPrice;
            Paid = order.PaidPrice.Value;
            OrderItems = order.OrderItems.ToList();
            BindDlOrderItems();
        }

        protected void dlOrderItems_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Footer)
            {
                Label lblTotalPrice = (Label)e.Item.FindControl("lblTotalPrice");
                lblTotalPrice.Text = Total.ToString();
                Label lblPaid = (Label)e.Item.FindControl("lblPaid");
                lblPaid.Text = Paid.ToString();
            }
        }

        private void BindDlOrderItems()
        {
            dlOrderItems.DataSource = OrderItems;
            dlOrderItems.DataBind();
            decimal? totalPerItem = 0;
            OrderItem item = new OrderItem();
            for (int i = 0; i < OrderItems.Count; i++)
            {
                item = OrderItems[i];
                Label lblTotalPerItem = (Label)dlOrderItems.Items[i].FindControl("lblItemTotal");
                if (lblTotalPerItem != null)
                {
                    totalPerItem = item.ItemCount * item.UnitPrice;
                    lblTotalPerItem.Text = totalPerItem.ToString();
                }
            }
        }
    }
}